﻿using EasyNet.Componets.Core.Zips;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyNet.Componets.Zips
{
    public class SharpCodeZip : IZip
    {
        #region 压缩
        public MemoryStream Compression(List<string> files)
        {
            MemoryStream ms = new MemoryStream();
            using (var s = new ZipOutputStream(ms))
            {
                s.SetLevel(6);

                foreach (string fileOrDir in files)
                {
                    ZipFileWithStream(fileOrDir, s);
                }
                s.Finish();
                s.Close();
            }
            
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }

        public void Compression(List<string> files, string zipPath)
        {
            if (File.Exists(zipPath))
            {
                File.Delete(zipPath);
            }
            using (var s = new ZipOutputStream(File.Create(zipPath)))
            {
                s.SetLevel(6);
     
                foreach (string fileOrDir in files)
                {
                    ZipFileWithStream(fileOrDir, s);
                }
                s.Finish();
                s.Close();
            }
        }

        /// <summary>
        /// 带压缩流压缩单个文件
        /// </summary>
        /// <param name="fileToZip">要进行压缩的文件名</param>
        /// <param name="zipStream"></param>
        /// <returns></returns>
        private void ZipFileWithStream(string fileToZip, ZipOutputStream zipStream)
        {
            //如果文件没有找到，则报错
            if (!File.Exists(fileToZip))
            {
                throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
            }
            //FileStream fs = null;
            FileStream zipFile = null;
            ZipEntry zipEntry = null;
            try
            {
                zipFile = File.OpenRead(fileToZip);
                byte[] buffer = new byte[zipFile.Length];
                zipFile.Read(buffer, 0, buffer.Length);
                zipFile.Close();
                zipEntry = new ZipEntry(Path.GetFileName(fileToZip));
                zipStream.PutNextEntry(zipEntry);
                zipStream.Write(buffer, 0, buffer.Length);
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (zipEntry != null)
                {
                }

                if (zipFile != null)
                {
                    zipFile.Close();
                }
                GC.Collect();
                GC.Collect(1);
            }

        }

        #endregion

        #region 提取
        public void Extract(string zipPath, string extractPath)
        {
            if (zipPath == string.Empty)
            {
                throw new Exception("压缩文件不能为空！");
            }
            if (!File.Exists(zipPath))
            {
                throw new FileNotFoundException("压缩文件不存在！");
            }

            //解压文件夹为空时默认与压缩文件同一级目录下，跟压缩文件同名的文件夹  
            if (extractPath == string.Empty)
                extractPath = zipPath.Replace(Path.GetFileName(zipPath), Path.GetFileNameWithoutExtension(zipPath));
            if (!extractPath.EndsWith("/"))
                extractPath += "/";
            if (!Directory.Exists(extractPath))
                Directory.CreateDirectory(extractPath);

            using (var s = new ZipInputStream(File.OpenRead(zipPath)))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(extractPath + directoryName);
                    }
                    if (directoryName != null && !directoryName.EndsWith("/"))
                    {
                    }
                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(extractPath + theEntry.Name))
                        {

                            int size;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }


        }
        #endregion
    }
}
